<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="courseForm" :rules="rules" ref="courseRef" label-width="100px" class="courseForm">
        <el-form-item label="课程类型" prop="coursestype">
          <el-select v-model="courseForm.coursestype" class="m-2" placeholder="请选择课程类型" size="large">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="coursesname">
          <el-input style="width: 300px" v-model="courseForm.coursesname" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程讲师" prop="courseslecturer">
          <el-input style="width: 300px" v-model="courseForm.courseslecturer" placeholder="请输入讲师"></el-input>
        </el-form-item>
        <el-form-item label="课程价格" prop="originalprice">
          <el-input type="number" min="0" style="width: 300px" v-model="courseForm.originalprice" placeholder="请输入课程价格"></el-input>
        </el-form-item>
        <el-form-item label="课程售卖价" prop="sellingprice">
          <el-input type="number" min="0" style="width: 300px" v-model="courseForm.sellingprice" placeholder="请输入课程售价"></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="coursessellstatus">
          <el-radio-group v-model="courseForm.coursessellstatus">
            <el-radio label="0">下架</el-radio>
            <el-radio label="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推荐状态" prop="coursesrecommend">
          <el-radio-group v-model="courseForm.coursesrecommend">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="课程主图" prop="coursescoverimg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="courseForm.coursescoverimg" :src="courseForm.coursescoverimg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item required label="课程副图" prop="coursesimg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUploadImg"
            :on-success="handleUrlSuccessImg"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="courseForm.coursesimg" :src="courseForm.coursesimg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程简介">
          <div ref='editor'></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer, hasEmoji } from '@/utils'
export default {
  name: 'Addcourse',
  setup() {
    const { proxy } = getCurrentInstance()
    // console.log('proxy', proxy)
    const editor = ref(null)
    const courseRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { id } = route.query
   
    const state = reactive({
      uploadImgServer,
      token: localGet('token') || '',
      id: id,
      courseForm: {
        coursesname: '',
        originalprice: '',
        sellingprice: '',
        coursessellstatus: '0',
        coursescoverimg: '',
        coursestype:'',
        coursesimg:'',
        coursesrecommend: '0',
        courseslecturer: ''
      },
      rules: {
        coursescoverimg: [
          { required: 'true', message: '请上传主图', trigger: ['change'] }
        ],
        coursesimg: [
          { required: 'true', message: '请上传副图', trigger: ['change'] }
        ],
        coursesname: [
          { required: 'true', message: '请填写课程名称', trigger: ['change'] }
        ],
        originalprice: [
          { required: 'true', message: '请填写课程价格', trigger: ['change'] }
        ],
        sellingprice: [
          { required: 'true', message: '请填写课程售价', trigger: ['change'] }
        ],
        coursestype: [
          { required: 'true', message: '请填写课程类型', trigger: ['change'] }
        ],
      },
      options : [
      {
        value: 1,
        label: '个人成长',
      },
      {
        value: 2,
        label: '亲密关系',
      },
      {
        value: 3,
        label: '亲子关系',
      },
      {
        value: 4,
        label: '情绪管理',
      },
      {
        value: 5,
        label: '最新上线',
      },
       {
        value: 6,
        label: '流派入门',
      },
       {
        value: 7,
        label: '实操进阶',
      },
       {
        value: 8,
        label: '新手必备',
      },
       {
        value: 9,
        label: '咨询专业课',
      }
    ]
    })
    let instance
    onMounted(() => {
      instance = new WangEditor(editor.value)
      instance.config.showLinkImg = false
      instance.config.showLinkImgAlt = false
      instance.config.showLinkImgHref = false
      instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance.config.uploadFileName = 'file'
      instance.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同，需要自定义返回格式
      instance.config.uploadImgHooks = {
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      instance.config.uploadImgServer = uploadImgsServer
      Object.assign(instance.config, {
        onchange() {
          console.log('change')
        },
      })
      instance.create()
      if (id) {
        console.log(id);
        axios.get(`/courses/${id}`).then(res => {
          // console.log(res,123);
          // const { courses, firstCategory, secondCategory, thirdCategory } = res
          // console.log('courses',courses)
          const courses = res;

          state.courseForm = {
            coursesname: courses.coursesname,
            originalprice: courses.originalprice,
            sellingprice: courses.sellingprice,
            coursessellstatus: String(courses.coursessellstatus),
            coursescoverimg: proxy.$filters.prefix(courses.coursescoverimg),
            coursestype:courses.coursestype,
            coursesimg:proxy.$filters.prefix(courses.coursesimg),
            coursesrecommend: String(courses.coursesrecommend),
            courseslecturer: courses.courseslecturer
          }
          console.log(proxy.$filters.prefix(courses.coursescoverimg)+'00');
          if (instance) {
            // 初始化课程详情 html
            instance.txt.html(courses.coursesdetailcontent)
          }
        })
      }
    })
    onBeforeUnmount(() => {
      instance.destroy()
      instance = null
    })
    const submitAdd = () => {
      courseRef.value.validate((vaild) => {
        if (vaild) {
          // 默认新增用 post 方法
          let httpOption = axios.post
          let params = {
            coursescoverimg: state.courseForm.coursescoverimg,
            coursesdetailcontent: instance.txt.html(),
            coursesname: state.courseForm.coursesname,
            coursessellstatus: state.courseForm.coursessellstatus,
            originalprice: state.courseForm.originalprice,
            sellingprice: state.courseForm.sellingprice,
            coursestype:state.courseForm.coursestype,
            coursesimg:state.courseForm.coursesimg,
            coursesrecommend: state.courseForm.coursesrecommend,
            courseslecturer: state.courseForm.courseslecturer
          }
          if (params.coursesname.length > 128) {
            ElMessage.error('课程名称不能超过128个字符')
            return
          }
          console.log('params', params)
          if (id) {
            params.id = id
            // 修改课程使用 put 方法
            httpOption = axios.put
          }
          httpOption('/courses', params).then(() => {
            ElMessage.success(id ? '修改成功' : '添加成功')
            router.push({ path: '/good' })
          })
        }
      })
    }
    const handleBeforeUpload = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleBeforeUploadImg = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleUrlSuccess = (val) => {
      state.courseForm.coursescoverimg = val.data || ''
    }
    const handleUrlSuccessImg = (val) => {
      state.courseForm.coursesimg = val.data || ''
    }
    return {
      ...toRefs(state),
      courseRef,
      submitAdd,
      handleBeforeUpload,
      handleUrlSuccess,
      editor,
      handleUrlSuccessImg,
      handleBeforeUploadImg
    }
  }
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
</style>